package com.netty.cn.model.ftp.channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * 
 * @author wangzonghui
 * @date 2021-08-06 10:50:35
 * @Description ftp channel
 */
public class FtpServletRequest extends SimpleChannelInboundHandler<FullHttpRequest> {

	final String GET_REQUEST = "GET";

	// 文件夹路劲自己设一个就行 我这里乱写了一个我maven仓库地址
	private String FILE_PATH;

	private final String CONTEXT_TYPE = "Context-type";

	private final String HTML_TYPE = "text/html;charset=UTF-8";

	private final String CONTENT_LENGTH = "Content-Length";

	public FtpServletRequest(String path) {
		this.FILE_PATH = path;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {

		// 获取用户的uri
		String uri = request.uri();
		String name = request.method().name();

		// 只支持GEt请求
		if (!GET_REQUEST.equals(name)) {
			// 响应浏览器
			responseError("只支持GET请求", channelHandlerContext);
			return;
		}

		File file = new File(FILE_PATH + URLDecoder.decode(uri, "UTF-8"));

		if (!file.exists()) {
			responseError(file+" 文件不存在。。。", channelHandlerContext);
			return;
		}

		if (file.isFile()) {
			// 如果是文件，执行下载
			responseFileCopy(file, channelHandlerContext);
		} else {
			// 如果是目录，显示子目录
			responseDir(channelHandlerContext, file, uri);
		}

	}

	/**
	 * 文件下载
	 * @param file
	 * @param channelHandlerContext
	 */
	private void responseFileCopy(File file, ChannelHandlerContext channelHandlerContext) {

		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.headers().add(CONTEXT_TYPE, "application/octet-stream");
		response.headers().add(CONTENT_LENGTH, file.length());

		Channel channel = channelHandlerContext.channel();

		FileInputStream ips = null;
		try {
			ips = new FileInputStream(file);
			byte[] by = new byte[1024];
			int read = -1;
			while ((read = ips.read(by, 0, by.length)) != -1) {
				response.content().writeBytes(by, 0, read);
			}
			channel.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ips != null) {
				try {
					ips.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 响应目录信息
	 * @param channelHandlerContext
	 * @param file
	 * @param uri
	 */
	private void responseDir(ChannelHandlerContext channelHandlerContext, File file, String uri) {

		StringBuffer buffer = new StringBuffer();
		// 获取目录的子文件
		File[] files = file.listFiles();
		
		if (!"/".equals(uri)) {
			uri+=File.separator;
		}
		for (File file1 : files) {
			if(file1.isDirectory()) {
				buffer.append("<li>📁<a href= '" + uri + file1.getName() + "'>" + file1.getName() + "</a></li>");
			}else {
				buffer.append("<li>📄<a href= '" + uri + file1.getName() + "'>" + file1.getName() + "</a></li>");
			}
		}
		responseClient(buffer.toString(), channelHandlerContext);
	}

	/**
	 * 响应客户端
	 * @param text
	 * @param channelHandlerContext
	 */
	public void responseClient(String text, ChannelHandlerContext channelHandlerContext) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

		System.out.println(text);
		// 设置响应头
		response.headers().add(CONTEXT_TYPE, HTML_TYPE);

		String msg = "<html><title>ftp文件分享</title> \t<meta charset=\"UTF-8\" />" + text + "</html>";

		try {
			response.content().writeBytes(msg.getBytes("UTF-8"));
			channelHandlerContext.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 响应错误信息
	 * @param text
	 * @param channelHandlerContext
	 */
	public void responseError(String text, ChannelHandlerContext channelHandlerContext) {
		String msg = "<h1>" + text + "</h1>";
		responseClient(msg, channelHandlerContext);
	}
}
